package com.ctg.sysmgr.sso.server.control.cookie;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class CookieController extends AbstractController{

	final public void addCookie(final HttpServletRequest request, final HttpServletResponse response) throws Exception{
		String path = request.getContextPath() + "/";
		
		addTGC2Cookie(request, response, path);

		addCASPRIVACY2Cookie(request, response, path);

		addJSESSIONID2Cookie(request, response, path);
	}
	
	private void addTGC2Cookie(final HttpServletRequest request, final HttpServletResponse response, String path){
		String tgc = request.getParameter("p1")==null?"":(String)request.getParameter("p1");
		if (!tgc.equals("")){
			Cookie c = new Cookie("TGC",tgc);
			c.setPath(path);
			c.setHttpOnly(true);
			c.setSecure(true);
			response.addCookie(c);
		}
	}
	
	private void addCASPRIVACY2Cookie(final HttpServletRequest request, final HttpServletResponse response, String path){
		String CASPRIVACY = request.getParameter("p2")==null?"":(String)request.getParameter("p2");
		if (!CASPRIVACY.equals("")){
			Cookie c = new Cookie("CASPRIVACY",CASPRIVACY);
			c.setPath(path);
			c.setHttpOnly(true);
			c.setSecure(true);
			response.addCookie(c);
		}
	}
	
	private void addJSESSIONID2Cookie(final HttpServletRequest request, final HttpServletResponse response, String path){
		String JSESSIONID = request.getParameter("p3")==null?"":(String)request.getParameter("p3");
		if (!JSESSIONID.equals("")){
			Cookie c = new Cookie("JSESSIONID",JSESSIONID);
			c.setPath(path);
			c.setHttpOnly(true);
			c.setSecure(true);
			response.addCookie(c);
		}
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		addCookie(request, response);
		return null;
	}

	
}
